﻿using System;
using UnityEngine;

[DisallowMultipleComponent]
public class MyLoopPage : MonoBehaviour
{
    [SerializeField]
    private NumChoose NumChoose;
    private Action OnFinished;
    ItemCallBack OnItemChange;

    private int m_MaxGoNum = 1;
    private int m_ItemGoNum =1;

    public int CurPageNum { get; private set; }
    public int MaxPageNum { get; private set; }

    void Awake()
    {
        if (NumChoose != null)
        {
            NumChoose.OnChange = SetCurPage;
        }
    }
    
    /// <summary>
    /// 刷新数据
    /// </summary>
    /// <param name="maxNum"></param>
    /// <param name="page"></param>
    public void RefreshData(int maxNum, int page = 1)
    {
        m_MaxGoNum = maxNum; CurPageNum = page;
        m_ItemGoNum = transform.childCount;
        if (m_MaxGoNum % m_ItemGoNum > 0)
        {
            MaxPageNum = m_MaxGoNum / m_ItemGoNum + 1;
        }
        else
        {
            MaxPageNum = m_MaxGoNum / m_ItemGoNum;
        }

        if (MaxPageNum == 0)
        {
            MaxPageNum = 1;
        }
        if (CurPageNum > MaxPageNum)
        {
            CurPageNum = 1;
        }

        if (NumChoose != null)
        {
            NumChoose.SetData(CurPageNum, MaxPageNum);
        }
        SetCurPage(CurPageNum);
    }

    /// <summary>
    /// 设置当前页签数据
    /// </summary>
    /// <param name="page"></param>
    public void SetCurPage(int page)
    {
        CurPageNum = page;
        int beginIdx = (page - 1) * m_ItemGoNum;
        int endIdx = beginIdx + m_ItemGoNum;
        if (endIdx > m_MaxGoNum) { endIdx = m_MaxGoNum; }

        for (int i = 0; i < m_ItemGoNum; i++)
        {
            var go = transform.GetChild(i).gameObject;
            Utility.SetActive(go, beginIdx + i < endIdx);
            if (beginIdx + i < endIdx && OnItemChange != null)
            {
                OnItemChange(go, beginIdx + i);
            }
        }

        if (NumChoose != null)
        {
            NumChoose.SetInputTxt(CurPageNum + "/" + MaxPageNum);
            NumChoose.SetBtnState(CurPageNum > 1, CurPageNum < MaxPageNum);
        }
        if (OnFinished != null) { OnFinished(); }
    }

    public void SetDelegate(ItemCallBack onItemChange, Action onFinished)
    {
        OnItemChange = onItemChange;
        OnFinished = onFinished;
    }
}